package io.renren.modules.api.service.impl;


import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import io.renren.common.exception.RRException;
import io.renren.common.validator.Assert;
import io.renren.modules.api.dao.UserDao;
import io.renren.modules.api.entity.UserEntity;
import io.renren.modules.api.service.UserService;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {
	@Autowired
	private UserDao userDao;
	
	@Override
	public UserEntity queryObject(Long userId){
		return userDao.selectById(userId);
	}
	
	@Override
	public List<UserEntity> queryList(Map<String, Object> map){
		JSONObject json = new JSONObject();
		json.putAll(map);
		UserEntity entityParam = JSON.toJavaObject(json, UserEntity.class);
		return userDao.selectList(new EntityWrapper<>(entityParam));
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		JSONObject json = new JSONObject();
		json.putAll(map);
		UserEntity entityParam = JSON.toJavaObject(json, UserEntity.class);
		return userDao.selectCount(new EntityWrapper<>(entityParam));
	}
	
	@Override
	public void save(String mobile, String password){
		UserEntity user = new UserEntity();
		user.setMobile(mobile);
		user.setUsername(mobile);
		user.setPassword(DigestUtils.sha256Hex(password));
		user.setCreateTime(new Date());
		userDao.insert(user);
	}
	
	@Override
	public void update(UserEntity user){
		userDao.updateById(user);
	}
	
	@Override
	public void delete(Long userId){
		userDao.deleteById(userId);
	}
	
	@Override
	public void deleteBatch(Long[] userIds){
		for(Long id:userIds) {
			userDao.deleteById(id);
		}
	}

	@Override
	public UserEntity queryByMobile(String mobile) {
		return userDao.queryByMobile(mobile);
	}

	@Override
	public long login(String mobile, String password) {
		UserEntity user = queryByMobile(mobile);
		Assert.isNull(user, "手机号或密码错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(password))){
			throw new RRException("手机号或密码错误");
		}

		return user.getUserId();
	}
}
